package com.tyc.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * 中断仅仅是给线程设置一个中断的标识（设置为true），线程还是会继续往下执行的。而线程怎么停止，则需要由我们自己去处理。
 * 线程默认状态为false
 * 调用interrupt()方法状态为true 抛出异常状态会将中断标志位清除
 * Thread.interrupted()会消除中断标志
 * 处理中断：
 *      1.抛出异常，让上层代码知道
 *      2.在捕获异常时，通过 interrupt 方法把中断状态重新设置为true(aqs处理中断)
 */
public class Testnterrupt {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("1:"+Thread.currentThread().isInterrupted());
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                System.out.println("2:"+Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println("3:"+Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println("4:"+Thread.currentThread().isInterrupted());
                // Thread.interrupted()会消除中断标志
                System.out.println("5:"+Thread.interrupted());
                Thread.interrupted();
                System.out.println("6:"+Thread.interrupted());
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
        thread.join();
    }
}
